package demo;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;

@WebServlet("/workServlet")
public class WorkServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取提交来的参数
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String age = req.getParameter("age");
        String jiguan = req.getParameter("address");
        String qq = req.getParameter("qq");
        String email = req.getParameter("email");
//        保存到文件中
//        获取域对象
        ServletContext context = getServletContext();
//        获取真实路径
        String realPath = context.getRealPath("add.txt");
//        获取输出流
        FileWriter fw = new FileWriter(realPath, true);
//        输出数据
        fw.write(name+","+sex+","+age+","+jiguan+","+qq+","+email);
//        输出换行
        fw.write(System.lineSeparator());
        fw.close();
        resp.setContentType("text/html;charset=utf-8");
//        保存
        resp.getWriter().write("保存成功");
    }
}
